package com.hichao.cs.chat.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.hichao.cs.base.controller.BaseController;
import com.hichao.cs.chat.service.ChatService;

@RestController
@RequestMapping("/chat")
public class ChatController extends BaseController {
	
    @Autowired
    private ChatService chatService;
	
	@RequestMapping(value="signin", method=RequestMethod.POST)
	public String signin(HttpServletRequest request) {
		this.DisplayHttpServletRequest(request);
		return this.chatService.signin();
	}

	@RequestMapping(value="signout", method=RequestMethod.POST)
	public String signout(HttpServletRequest request) {
		this.DisplayHttpServletRequest(request);
		return this.chatService.signout();
	}
	
	@RequestMapping(value="pull/{source}", method=RequestMethod.GET)
	public  String pull(HttpServletRequest request, 
			@PathVariable String source) {
		this.DisplayHttpServletRequest(request);
		Map<Long, String> result = this.chatService.pull(source);
		ObjectMapper mapper = new ObjectMapper();
		String rv = null;
		try {
			rv = mapper.writeValueAsString(result);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rv;
	}
	
	@RequestMapping(value="/push", method=RequestMethod.POST)
	public String push(HttpServletRequest request) {
		this.DisplayHttpServletRequest(request);
		String text= request.getParameter("text");
		String target= request.getParameter("target");
		return this.chatService.push(target, text);
	}
	
	@RequestMapping(value="/pushself", method=RequestMethod.POST)
	public String pushself(HttpServletRequest request) {
		this.DisplayHttpServletRequest(request);
		String text = request.getParameter("text");
		return this.chatService.pushself(text);
	}
}
